package com.bwie.job;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.es.EsProd;
import com.bwie.mapper.TbProdMapper;
import com.bwie.pojo.TbProd;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;

import java.util.List;

/**
 * @description :
 * @Author QiHainan
 * @Create 2025/4/7 19:59
 * @Version 1.0
 */
@Slf4j
public class SyncProdJob implements Job {

    @Autowired
    TbProdMapper tbProdMapper;
    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("quartz 定时任务【开始】");
        //先创建索引
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsProd.class);
        boolean exists = indexOps.exists();
        if(!exists){
            //不存在，创建索引
            indexOps.create();
            //创建映射
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }
        //从数据库中读取所有的商品数据
        List<TbProd> tbProds = tbProdMapper.selectList(null);
        //把商品信息存入Es中
        for (TbProd tbProd : tbProds) {
            EsProd esProd = BeanUtil.toBean(tbProd, EsProd.class);
            elasticsearchRestTemplate.save(esProd);
        }
        log.info("quartz 定时任务【结束】");
    }
}
